package com.duke.shaking.more;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

import com.duke.shaking.Constants;
import com.duke.shaking.R;
import com.duke.shaking.ResultCodeFactory;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.Order;
import com.duke.shaking.storage.DataManager;
import com.duke.shaking.utils.AppUtils;
import com.duke.shaking.utils.pay.PayStatusCode;
import com.duke.shaking.utils.pay.PayUtils;
import com.duke.shaking.utils.pay.Products;
import com.duke.shaking.utils.pay.ProductDetail;
import com.loopj.android.http.AsyncHttpClient;
import com.sohu.pay.order.OrderInfo;
import com.sohu.pay.ui.StartSohuPayActivity;

public class AccountActivity extends TitleActivity {

	private class Present {
		public int type;
		public int coins;
		public boolean used;
	}
	
	private int coins;
	private List<Present> presents;
	private Order currOrder;
	private List<Order> orders;
	private OrderAdapter orderAdapter;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        refreshAccount();
	}
	
	private void parseAccountResponse(JSONObject jsonObj) {
		if (jsonObj != null) {
			try {
				coins = jsonObj.getInt(NetUtils.ACCOUNT);
				showCoins(coins);
				JSONArray arr = jsonObj.optJSONArray(NetUtils.PRESENT);
				if (arr != null) {
					if (arr != null && arr.length() > 0) {
						List<Present> presents = new ArrayList<Present>();
						for(int i = 0; i < arr.length(); i ++) {
							Present p = new Present();
							p.type = arr.getJSONObject(i).optInt(NetUtils.ID);
							p.coins = arr.getJSONObject(i).optInt(NetUtils.NUMS);
							int used = arr.getJSONObject(i).optInt(NetUtils.USED);
							p.used = (used == 0 ? false : true);
							presents.add(p);
						}
						showPresents(presents);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
	}
	
	private void refreshAccount() {
		coins = -1;
        AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				super.onResultSuccess(response);
				JSONObject jsonObj = this.getBody(response);
				parseAccountResponse(jsonObj);
			}

			@Override
			public void onResultFailure(String result) {
				super.onResultFailure(result);
				
			}
        };
        AsyncHttpClient client = NetUtils.getAccountInfo(this, responseHandler);
        showProgress(R.string.progress_get_account, client, responseHandler);
	}
	
	@Override
	protected int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_account_free;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(TITLE_BTN_EXIST | TITLE_BTN_BACK,
				R.string.back,
				0,
				0,
				R.string.title_account);
	}
	
	public void switchFree(View v) {
		orderAdapter = null;
		setContentView(R.layout.activity_account_free);
		if (coins >= 0) {
			showCoins(coins);
		}
		if (presents != null) {
			showPresents(presents);
		}
	}
	
	public void switchBuy(View v) {
		orderAdapter = null;
		setContentView(R.layout.activity_account_buy);
		if (coins >= 0) {
			showCoins(coins);
		}
	}
	
	public void switchOrder(View v) {
		setContentView(R.layout.activity_account_order);
		if (coins >= 0) {
			showCoins(coins);
		}
		listOrders();
	}
	
	private void listOrders() {
		orders = DataManager.getShared().loadAllOrder();
		ListView lstOrders;
		if (orders != null && orders.size() > 0) {
			lstOrders = (ListView)findViewById(R.id.lst_orders);
			if (lstOrders != null) {
				orderAdapter = new OrderAdapter(this);
				orderAdapter.setDataSource(orders);
				lstOrders.setAdapter(orderAdapter);
				lstOrders.setOnItemLongClickListener(new OnItemLongClickListener() {
					public boolean onItemLongClick(AdapterView<?> parent, View view,
							int position, long id) {
						editOrder(position);
						return false;
					}
				});
			}
			queryUnfinOrders(orders);
		}
	}
	
	private void deleteOrder(int position) {
		if (orders == null || position < 0 || position >= orders.size()) {
			return;
		}
		Order order = orders.get(position);
		if (order != null && order.getOrderId() >= 0) {
			DataManager.getShared().removeOrder(order.getOrderId());
			if (orders.remove(order)) {
				if (orderAdapter != null) {
					orderAdapter.notifyDataSetChanged();
				}
			}
		}
	}
	
	public void editOrder(final int position) {
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				switch(which) {
				case 0:
					deleteOrder(position);
					break;
				}
			}
		};
		new AlertDialog.Builder(this)
			.setItems(R.array.order_edit_dlg_item, 
					listener)
			.show();
	}
	
	private void showCoins(int coins) {
		TextView txtCoins = (TextView)this.findViewById(R.id.txt_coins);
		if (txtCoins != null) {
			txtCoins.setText(String.valueOf(coins));
		}
	}
	
	private boolean isPresentUsed(int type) {
		for(Present p : presents) {
			if (type == p.type) {
				return p.used;
			}
		}
		return true;
	}
	
	private void showPresents(List<Present> presents) {
		this.presents = presents;
		int ids[] = {R.id.btn_get_now1, R.id.btn_get_now2};
		for (int id : ids) {
			ImageButton btn = (ImageButton)findViewById(id);
			if (btn != null) {
				try {
					String tag = (String)btn.getTag();
					int type = Integer.parseInt(tag);
					btn.setEnabled(!isPresentUsed(type));
				}
				catch(Exception exp) {
					
				}
			}
		}
		
	}
	
	private void pay(int productType, String orderNo, String orderTime, String sign) {
		if (orderNo == null || orderNo.equals("")
			|| orderTime == null
			|| sign == null || sign.equals("")) {
			return;
		}
		ProductDetail pd = Products.getProductDetail(productType);
		if (pd == null) {
			return;
		}
		OrderInfo orderInfo = PayUtils.createOrderInfo(productType, orderNo, orderTime, sign, this);
		Order order = new Order();
		order.setOrderNo(orderInfo.getOrderno());
		//order.setOrderTime(AppUtils.parseDate(orderInfo.getOrdertime()));
		order.setOrderTime(new Date());
		order.setProdectType(productType);
		long orderId = DataManager.getShared().putOrder(order);
		order.setOrderId(orderId);
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("orderInfo", orderInfo);
		intent.putExtras(bundle);
		intent.setClass(getApplicationContext(),
				StartSohuPayActivity.class);
		// intent.setClass(getApplicationContext(), SohuPay.class);
		currOrder = order;
		startActivityForResult(intent,
				Constants.INTENT_CODE_SOHU_PAY);
	}
	
	private void createOrder(final int productType) {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				super.onResultSuccess(response);
				JSONObject jsonObj = this.getBody(response);
				if (jsonObj != null) {
					try {
						String orderNo = jsonObj.getString(NetUtils.ORDERID);
						String orderTime = jsonObj.optString(NetUtils.ORDERTIME);
						String signKey = jsonObj.getString(NetUtils.SIGNKEY);
						pay(productType, orderNo, orderTime, signKey);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						toast(R.string.err_create_order_failed);
					}
				}
			}

			@Override
			public void onResultFailure(String result) {
				super.onResultFailure(result);
				toast(R.string.err_create_order_failed);
			}
        };
        AsyncHttpClient client = NetUtils.createOrder(this, responseHandler, String.valueOf(productType));
        showProgress(R.string.progress_submit_order, client, responseHandler);
	}
	
	public void buyCoins(View v) {
		if (v == null) {
			return;
		}
		try {
			String tag = (String)v.getTag();
			int productType = Integer.parseInt(tag);
			if (Products.getProductDetail(productType) == null) {
				return;
			}
			currOrder = null;
			createOrder(productType);
		}
		catch(Exception exp) {
			exp.printStackTrace();
		}
		
	}
	
	private void getFreeCoins(Present present) {
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				super.onResultSuccess(response);
				JSONObject jsonObj = this.getBody(response);
				parseAccountResponse(jsonObj);
				toast(R.string.get_free_coins_successfully);
			}

			@Override
			public void onResultFailure(String result) {
				super.onResultFailure(result);
				if (ResultCodeFactory.REQUEST_PHOTO_COUNT_ERROR.equals(result)) {
					toast(R.string.err_photo_not_enough);
				}
				else {
					toast(R.string.err_get_free_coins_failed);
				}
			}
        };
        AsyncHttpClient client = NetUtils.getFreeCoins(this, responseHandler, present.type, "");
        showProgress(R.string.progress_get_free_coins, client, responseHandler);
	}
	
	public void getFree(View v) {
		if (v == null) {
			return;
		}
		try {
			String tag = (String)v.getTag();
			int type = Integer.parseInt(tag);
			if (presents == null) {
				return;
			}
			Present present = null;
			for (Present p : presents) {
				if (p.type == type) {
					present = p;
				}
			}
			if (present == null) {
				return;
			}
			if (present.used) {
				toast(R.string.free_coins_got);
				return;
			}
			getFreeCoins(present);
		}
		catch(Exception exp) {
			exp.printStackTrace();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		Bundle extras = null;
		Order order = null;
		switch (requestCode) {
		case Constants.INTENT_CODE_SOHU_PAY:
			order = currOrder;
			currOrder = null;
			if (intent != null) {
				extras = intent.getExtras();
				if (extras != null) {
					String result = extras.getString("result");
					info("mainSohu #: " + result);
					int descId = PayStatusCode.getStatusDesc(extras
							.getString("result"));
					order.setPayStatusCode(result);
					if (result != null && result.equals(PayStatusCode.PAY_STATUS_CODE_SUCCEED)) {
						if (order != null && order.getOrderId() >= 0 && order.getOrderNo() != null) {
							order.setOrderState(Order.ORDER_STATE_DONE);
							DataManager.getShared().updateOrderState(order);
						}
						refreshAccount();
						toast(descId);
					}
					else {
						toast(getString(R.string.err_pay_failed) + getString(descId));
						if (order != null && order.getOrderId() >= 0 && order.getOrderNo() != null) {
							order.setOrderState(Order.ORDER_STATE_FAIL);
							DataManager.getShared().updateOrderState(order);
						}
					}
				}
			}
			break;
		}
	}
	
	private void refreshOrderState(Order order) {
		if (orders != null 
			&& orders.contains(order)) {
			if (orderAdapter != null) {
				orderAdapter.notifyDataSetChanged();
			}
		}
	}
	
	private void queryUnfinOrders(List<Order> orders) {
		for (Order order : orders) {
			if (order != null && order.getOrderNo() != null) {
				OrderQueryResultHandler orderHanlder = new OrderQueryResultHandler(order);
				NetUtils.queryOrder(this, orderHanlder, order.getOrderNo());
			}
		}
	}
	
	private class OrderQueryResultHandler extends AsyncHttpResponseWithResultHandler {
		private Order order;
		
		public OrderQueryResultHandler(Order order) {
			this.order = order;
		}
		@Override
		public void onResultSuccess(String response) {
			super.onResultSuccess(response);
			JSONObject jsonObj = this.getBody(response);
			if (order != null) {
				String payResult = jsonObj.optString(NetUtils.PAYRESULT);
				if ("1".equals(payResult)) {
					order.setOrderState(Order.ORDER_STATE_DONE);
				}
				else {
					order.setOrderState(Order.ORDER_STATE_FAIL);
				}
				order.setPayResult(payResult);
				DataManager.getShared().updateOrderState(order);
				refreshOrderState(order);
			}
		}

		@Override
		public void onResultFailure(String result) {
			super.onResultFailure(result);
			if (order != null) {
				order.setOrderState(Order.ORDER_STATE_QUERY_FAILED);
				refreshOrderState(order);
			}
		}
		
		@Override
		public void onFailure(Throwable arg0, String arg1) {
			super.onFailure(arg0, arg1);
			if (order != null) {
				order.setOrderState(Order.ORDER_STATE_QUERY_FAILED);
				refreshOrderState(order);
			}
		}
	}

}
